package aliyun

import (
	"fmt"
	"os"

	"gitee.com/smalldeng/cloud-station-g7/store"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var (
	_ store.Uploader = &AliOssStore{}
)

type AliOssStore struct {
	client   *oss.Client
	listener oss.ProgressListener
}

type Options struct {
	Endpoint     string
	AccessKey    string
	AccessSecret string
}

func (o *Options) Validate() error {
	if o.Endpoint == "" || o.AccessKey == "" || o.AccessSecret == "" {
		return fmt.Errorf("please set env ALI_AK,ALI_SK,ALI_OSS_ENDPOINT")
	}
	return nil
}

func NewAliOssStoreWithDefault() (*AliOssStore, error) {
	return NewAliOssStore(&Options{
		Endpoint:     os.Getenv("ALI_OSS_ENDPOINT"),
		AccessKey:    os.Getenv("ALI_AK"),
		AccessSecret: os.Getenv("ALI_SK"),
	})
}

func NewAliOssStore(opts *Options) (*AliOssStore, error) {
	if err := opts.Validate(); err != nil {
		return nil, err
	}
	c, err := oss.New(opts.Endpoint, opts.AccessKey, opts.AccessSecret)
	if err != nil {
		return nil, err
	}
	return &AliOssStore{
		client: c,
	}, nil

}

func (a *AliOssStore) Upload(BucketName string, objectKey string, fileName string) error {
	bucket, err := a.client.Bucket(BucketName)
	if err != nil {
		return err
	}
	if err := bucket.PutObjectFromFile(objectKey, fileName, oss.Progress(a.listener)); err != nil {
		return err
	}

	downloadURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 60*60*24)
	if err != nil {
		return err
	}
	fmt.Printf("文件下载地址%s", downloadURL)
	return nil
}
